package com.stellar.circle.interceptor;

import com.stellar.core.context.LoginContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
public class WebSocketAuthInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        // 从请求头中获取网关传递的用户ID
        String userIdHeader = request.getHeaders().getFirst(LoginContextHolder.LOGIN_USER_HEADER);
        if (StringUtils.isEmpty(userIdHeader)) {
            return false;
        }

        try {
            Long userId = Long.parseLong(userIdHeader);
            attributes.put("userId", userId);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        // 握手后处理
    }
}